package cn.kent.base.instructionRearrangement;

/**
 * 测试Java指令重排
 * 多线程下指令重排可能会导致结果和预想结果不同，使用volatile修饰可以避免重排序和内存可见性问题。
 * 写操作：会保证volatile修饰的变量之前的操作没有重排序。
 * 读操作：会保证volatile修饰的变量之后的操作没有重排序。
 */
public class TestInstructionRearrangement {

    private static int num = 0;
    private static volatile boolean ready = false;

    public static class ReadThread extends Thread {
        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                if (ready) {
                    System.out.println(num + num);
                }
                System.out.println("read thread ...");
            }
        }
    }


    public static class WriteThread extends Thread {
        @Override
        public void run() {
            num = 2;
            ready = true;
            System.out.println("write thread over...");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ReadThread readThread = new ReadThread();
        WriteThread writeThread = new WriteThread();
        readThread.start();
        writeThread.start();
        Thread.sleep(10);
        readThread.interrupt();
        System.out.println("main over...");
    }
}
